package com.bestcem.xm.user.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.alibaba.fastjson.JSON;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.user.constant.CommonConstant;
import com.bestcem.xm.user.dao.UserRoleDao;
import com.bestcem.xm.user.entity.pojo.GetAccountRoleDO;
import com.bestcem.xm.user.entity.pojo.UserRoleDO;
import com.bestcem.xm.user.enums.*;
import com.bestcem.xm.user.grpc.client.PackageGrpcService;
import com.bestcem.xm.user.service.*;
import com.bestcem.xm.user.service.dto.group.IdRelationDTO;
import com.bestcem.xm.user.service.dto.role.*;
import com.bestcem.xm.user.service.dto.user.OrganizationDTO;
import com.bestcem.xm.user.util.business.DataBaseUtil;
import com.bestcem.xm.user.util.business.UserPermissionUtil;
import com.bestcem.xm.user.util.convert.UserRoleConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色 service
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/14 13:18
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private UserRoleDao userRoleDao;

    @Resource
    private UserRoleConvert userRoleConvert;

    @Resource
    private PackageGrpcService packageGrpcService;

    @Resource
    private RolePermissionService rolePermissionService;

    @Resource
    private UserUserRoleService userUserRoleService;

    @Resource
    private UserPermissionUtil permissionUtil;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private UserGroupService userGroupService;

    @Override
    public ServiceResult<String> getAdminRole(String orgId) {
        // 校验参数
        if (!ObjectId.isValid(orgId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "org_id 参数不正确");
        }
        // 设置查询条件
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setOrgId(orgId);
        userRoleDTO.setName(RolePermsEnum.ADMIN.getName());
        userRoleDTO.setType(RolePermsEnum.ADMIN.getType());
        // 查询并返回结果
        return this.getRoleIdByCondition(userRoleDTO);
    }

    @Override
    public ServiceResult<String> getSeniorAdminRole(String orgId) {
        // 校验参数
        if (!ObjectId.isValid(orgId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "org_id 参数不正确");
        }
        // 设置查询条件
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setOrgId(orgId);
        userRoleDTO.setName(RolePermsEnum.SENIOR_ADMIN.getName());
        userRoleDTO.setType(RolePermsEnum.SENIOR_ADMIN.getType());
        // 查询并返回结果
        return this.getRoleIdByCondition(userRoleDTO);
    }

    @Override
    public ServiceResult<String> getDeliverCheckRole(String orgId) {
        // 校验参数
        if (!ObjectId.isValid(orgId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "org_id 参数不正确");
        }
        // 设置查询条件
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setOrgId(orgId);
        userRoleDTO.setName(RolePermsEnum.DELIVER_CHECK.getName());
        userRoleDTO.setType(RolePermsEnum.DELIVER_CHECK.getType());
        // 查询并返回结果
        ServiceResult<String> roleIdByCondition = getRoleIdByCondition(userRoleDTO);
        if (StringUtils.isEmpty(roleIdByCondition.getData())) {
            // 不存在投放审核角色则创建系统内置的投放审核角色和对应的权限
            ServiceResult<UserRoleDTO> createDeliverCheckRoleRt = createDeliverCheckRole(orgId);
            return ServiceResult.success(createDeliverCheckRoleRt.getData().getRoleId());
        } else{
            return roleIdByCondition;
        }
    }

    @Override
    public ServiceResult<List<RoleListDTO>> getRoleListByOrgId(String orgId) {
        UserRoleDO roleDO = new UserRoleDO();
        roleDO.setOrgId(orgId);
        roleDO.setType(RoleTypeEnum.COMMON.getType());
        roleDO.setBiShare(RoleBiShareEnum.NO_SHARE.getType());
        List<UserRoleDO> roleList = userRoleDao.selectRoleByCondition(roleDO);
        List<RoleListDTO> roleListDTO = userRoleConvert.dolist2Dtolist(roleList);
        return ServiceResult.success(roleListDTO);

    }

    @Override
    public ServiceResult<String> saveUserRole(UserRoleDTO saveRoleDTO) {

        UserRoleDO roleDO = new UserRoleDO();
        roleDO.setOrgId(saveRoleDTO.getOrgId());
        roleDO.setName(saveRoleDTO.getName());
        List<UserRoleDO> roleList = userRoleDao.selectRoleByCondition(roleDO);
        if (CollectionUtils.isNotEmpty(roleList)) {
            return ServiceResult.fail("角色名称已存在");
        }
        Date now = DataBaseUtil.getDate();
        saveRoleDTO.setStatus(RoleStatusEnum.ACTIVATED.getType());
        saveRoleDTO.setType(RoleTypeEnum.COMMON.getType());
        saveRoleDTO.setBiShare(RoleBiShareEnum.NO_SHARE.getType());
        saveRoleDTO.setCreateTime(now);
        saveRoleDTO.setUpdateTime(now);
        saveRoleDTO.setCreatorId(saveRoleDTO.getCreatorId());
        saveRoleDTO.setOperatorId(saveRoleDTO.getOperatorId());
        saveRoleDTO.setOrgId(saveRoleDTO.getOrgId());
        // 保存角色
        this.saveUserRoleBase(saveRoleDTO);
        // 保存权限
        RolePermissionDTO permissionDTO = new RolePermissionDTO();
        permissionDTO.setRoleId(saveRoleDTO.getRoleId());
        permissionDTO.setOrgId(saveRoleDTO.getOrgId());
        permissionDTO.setCreatorId(saveRoleDTO.getCreatorId());
        permissionDTO.setOperatorId(saveRoleDTO.getOperatorId());
        permissionDTO.setCreateTime(now);
        permissionDTO.setUpdateTime(now);
        rolePermissionService.insertSelective(permissionDTO);
        return ServiceResult.success(saveRoleDTO.getRoleId());
    }

    @Override
    public ServiceResult<String> saveUserRoleBase(UserRoleDTO saveRoleDTO) {
        // 默认缺省值参数设置
        saveRoleDTO.setBiShare(saveRoleDTO.getBiShare() == null ? RoleBiShareEnum.NO_SHARE.getType() : saveRoleDTO.getBiShare());
        saveRoleDTO.setStatus(saveRoleDTO.getStatus() == null ? RoleStatusEnum.ACTIVATED.getType() : saveRoleDTO.getStatus());
        saveRoleDTO.setType(saveRoleDTO.getType() == null ? RoleTypeEnum.COMMON.getType() : saveRoleDTO.getType());

        // 保存角色
        String roleId = userRoleDao.saveUserRole(userRoleConvert.dtoToDo(saveRoleDTO));
        // 设置返回值
        saveRoleDTO.setRoleId(roleId);
        return ServiceResult.success(saveRoleDTO.getRoleId());
    }

    @Override
    public ServiceResult<Integer> updateUserRoleBase(UserRoleDTO userRoleDTO) {
        Integer result = userRoleDao.updateRoleByPrimaryKeySelective(userRoleConvert.dtoToDo(userRoleDTO));
        if (result > 0) {
            return ServiceResult.success(result);
        }
        return ServiceResult.fail("更新失败");
    }

    @Override
    public ServiceResult<List<GetAccountRoleDTO>> getAccountRoleCount(String roleId, String orgId, String userId) {
        ServiceResult<Integer> checkSenior = userBusinessService.checkSenior(userId, orgId);
        ServiceResult<Integer> checkSuper = userBusinessService.checkSuper(userId, orgId);
        List<String> childrenGroupIds = new ArrayList<>();
        // 判断是否是高级管理员或系统管理员
        if (!(checkSenior.getData().equals(NumberUtils.INTEGER_ONE) || checkSuper.getData().equals(NumberUtils.INTEGER_ONE))) {
            // 当前组及子组织id
            ServiceResult<List<String>> serviceResult = userGroupService.getChildrenGroupIdsByUserId(orgId, userId);
            childrenGroupIds = serviceResult.getData();
        }
        List<GetAccountRoleDO> userList = userRoleDao.getAccountRoleCount(roleId, childrenGroupIds, UserStatusEnum.ACTIVATED.getStatus());
        return ServiceResult.success(userRoleConvert.getAccountRoleDO2DTO(userList));

    }

    @Override
    public ServiceResult<Integer> updateUserRole(UpdateRoleDTO roleDTO) {
        ServiceResult<String> result = getAdminRole(roleDTO.getOrgId());
        String adminRoleId = result.getData();
        ServiceResult<String> seniorAdminRole = getSeniorAdminRole(roleDTO.getOrgId());
        String seniorId = seniorAdminRole.getData();
        if (roleDTO.getRoleId().equals(adminRoleId) || roleDTO.getRoleId().equals(seniorId)) {
            ServiceResult.fail(ResourceErrorCodeEnum.UPDATE_FORBID, "cannot update super role");
        }
        Date now = new Date();
        // 判断角色名称是否重复
        UserRoleDO roleDO = new UserRoleDO();
        roleDO.setName(roleDTO.getName());
        roleDO.setOrgId(roleDTO.getOrgId());
        List<UserRoleDO> userRoleList = userRoleDao.selectRoleByCondition(roleDO);
        if (CollectionUtils.isNotEmpty(userRoleList) && !userRoleList.get(0).getRoleId().equals(roleDTO.getRoleId())) {
            return ServiceResult.fail("角色名称已存在");
        }
        //此处权限拆分为另一个接口
        /*ServiceResult<RolePermissionDTO> permissionResult = rolePermissionService.selectByOrgIdAndRoleId(roleDTO.getOrgId(), roleDTO.getRoleId());
        RolePermissionDTO rolePermission = permissionResult.getData();
        if (Objects.isNull(rolePermission)) {
            // 保存权限
            RolePermissionDTO permissionDTO = new RolePermissionDTO();
            permissionDTO.setRoleId(roleDTO.getRoleId());
            permissionDTO.setOrgId(roleDTO.getOrgId());
            permissionDTO.setPermission(roleDTO.getPermission().toJSONString());
            permissionDTO.setCreatorId(roleDTO.getOperatorId());
            permissionDTO.setOperatorId(roleDTO.getOperatorId());
            permissionDTO.setCreateTime(now);
            permissionDTO.setUpdateTime(now);
            rolePermissionService.insertSelective(permissionDTO);
        } else {
            // 更新权限
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
            rolePermissionDTO.setRolePermissionId(rolePermission.getRolePermissionId());
            rolePermissionDTO.setPermission(roleDTO.getPermission().toJSONString());
            rolePermissionDTO.setUpdateTime(DataBaseUtil.getDate());
            rolePermissionDTO.setOperatorId(roleDTO.getOperatorId());
            rolePermissionService.updateByPrimaryKeySelective(rolePermissionDTO);
        }*/
        // 更新角色
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setRoleId(roleDTO.getRoleId());
        userRoleDTO.setRoleIndex(roleDTO.getRoleIndex());
        userRoleDTO.setName(roleDTO.getName());
        userRoleDTO.setUpdateTime(now);
        userRoleDTO.setOperatorId(roleDTO.getOperatorId());
        return updateUserRoleBase(userRoleDTO);
    }

    @Override
    public ServiceResult<Integer> deleteUserRole(String orgId, String roleId) {
        ServiceResult<String> result = getAdminRole(orgId);
        String adminRoleId = result.getData();
        if (roleId.equals(adminRoleId)) {
            return ServiceResult.fail(ResourceErrorCodeEnum.UPDATE_FORBID, "cannot update super role");
        }
        // 删除角色时，删除角色管理用户表ds_user_userrole
        userUserRoleService.deleteByRoleId(roleId);
        // 删除角色
        return ServiceResult.success(userRoleDao.deleteRoleByPrimaryKey(roleId));
    }

    @Override
    public ServiceResult<List<UserRoleDTO>> selectByCondition(UserRoleDTO userRoleDTO) {
        // 校验参数
        if (userRoleDTO == null) {
            return ServiceResult.fail("参数为空");
        }
        userRoleDTO.setStatus(RoleStatusEnum.ACTIVATED.getType());

        // 查询并返回结果
        return ServiceResult.success(userRoleConvert.dos2Dtos(userRoleDao.selectRoleByCondition(userRoleConvert.dtoToDo(userRoleDTO))));
    }

    @Override
    public ServiceResult<String> copySample(String srcOrgId, OrganizationDTO dstOrg) {
        // 查询源公司的所有角色
        UserRoleDTO querySrcRoleDTO = new UserRoleDTO();
        querySrcRoleDTO.setOrgId(srcOrgId);
        List<UserRoleDTO> srcRoles = this.selectByCondition(querySrcRoleDTO).getData();
        if (CollectionUtils.isEmpty(srcRoles)) {
            return ServiceResult.success();
        }
        // 检查该公司的套餐是否含有客户旅程模块，copy_sample预置角色首页
        Boolean hasCustomerJourney = packageGrpcService.hasCustomerJourneyModule(dstOrg.getPackageId());
        // copy role
        for (UserRoleDTO srcRole : srcRoles) {
            UserRoleDTO userRoleDTO = new UserRoleDTO();
            userRoleDTO.setOrgId(dstOrg.getOrgId());
            userRoleDTO.setUpdateTime(dstOrg.getUpdateTime());
            userRoleDTO.setOperatorId(dstOrg.getOperatorId());
            // 判断是否是系统管理员
            if (RolePermsEnum.ADMIN.getName().equals(srcRole.getName()) && Boolean.TRUE.equals(hasCustomerJourney)) {
                userRoleDTO.setRoleIndex(RoleIndexEnum.CJM.getType());
                // 更新角色
                this.updateUserRoleBase(userRoleDTO);
                continue;
            }
            userRoleDTO.setName(srcRole.getName());
            userRoleDTO.setStatus(srcRole.getStatus());
            userRoleDTO.setType(srcRole.getType());
            userRoleDTO.setContent(srcRole.getContent());
            userRoleDTO.setRoleIndex("全功能查看".equals(srcRole.getName()) && Boolean.TRUE.equals(hasCustomerJourney) ? RoleIndexEnum.CJM.getType() : null);

            // 通过角色名称和orgId查询角色
            UserRoleDTO queryRoleDTO = new UserRoleDTO();
            queryRoleDTO.setOrgId(userRoleDTO.getOrgId());
            queryRoleDTO.setName(userRoleDTO.getName());
            List<UserRoleDTO> existRoles = this.selectByCondition(queryRoleDTO).getData();
            if (CollectionUtils.isNotEmpty(existRoles)) {
                // 更新角色
                UserRoleDTO existRole = existRoles.get(0);
                userRoleDTO.setRoleId(existRole.getRoleId());
                this.updateUserRoleBase(userRoleDTO);
            } else {
                // 创建角色
                // 设置参数
                userRoleDTO.setCreateTime(userRoleDTO.getUpdateTime());
                userRoleDTO.setCreatorId(userRoleDTO.getOperatorId());
                this.saveUserRoleBase(userRoleDTO);
            }

            // 通过源公司的角色id查询角色的权限
            RolePermissionDTO srcRolePermDTO = rolePermissionService.selectByOrgIdAndRoleId(srcRole.getOrgId(), srcRole.getRoleId()).getData();
            if (srcRolePermDTO == null) {
                continue;
            }

            // 如果角色权限存在的话就copy角色权限到目标公司
            RolePermissionDTO existRolePermission = rolePermissionService.selectByOrgIdAndRoleId(userRoleDTO.getOrgId(), userRoleDTO.getRoleId()).getData();
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
            rolePermissionDTO.setUpdateTime(userRoleDTO.getUpdateTime());
            rolePermissionDTO.setOperatorId(userRoleDTO.getOperatorId());
            rolePermissionDTO.setPermission(srcRolePermDTO.getPermission());
            if (existRolePermission != null) {
                // 更新角色权限
                rolePermissionDTO.setRolePermissionId(existRolePermission.getRolePermissionId());
                rolePermissionService.updateByPrimaryKeySelective(rolePermissionDTO);
            } else {
                // 新增角色权限
                rolePermissionDTO.setRoleId(userRoleDTO.getRoleId());
                rolePermissionDTO.setOrgId(userRoleDTO.getOrgId());
                rolePermissionDTO.setCreateTime(userRoleDTO.getUpdateTime());
                rolePermissionDTO.setCreatorId(userRoleDTO.getOperatorId());
                rolePermissionService.insertSelective(rolePermissionDTO);
            }
        }

        return ServiceResult.success();
    }

    @Override
    public ServiceResult<UserRoleDTO> createAdminRole(OrganizationDTO organizationDTO) {
        // 保存系统管理员角色以及对应的权限
        return this.createRoleByRolePermsEnum(organizationDTO, RolePermsEnum.ADMIN);
    }


    @Override
    public ServiceResult<List<IdRelationDTO>> listSampleRoleIds(String srcId, String dstId) {
        ArrayList<IdRelationDTO> relationDTOS = new ArrayList<>();
        UserRoleDO srcRole = new UserRoleDO();
        srcRole.setOrgId(srcId);
        List<UserRoleDO> userRoleDOList = userRoleDao.selectRoleByCondition(srcRole);
        for (UserRoleDO userRoleDO : userRoleDOList) {
            UserRoleDO userRole = new UserRoleDO();
            userRole.setOrgId(dstId);
            userRole.setName(userRoleDO.getName());
            UserRoleDO dstRole = userRoleDao.selectRoleByCondition(userRole).get(0);
            if (null != dstRole) {
                IdRelationDTO idRelationDTO = IdRelationDTO.builder()
                        .oldId(userRoleDO.getRoleId())
                        .newId(dstRole.getRoleId())
                        .build();
                relationDTOS.add(idRelationDTO);
            }
        }
        return ServiceResult.success(relationDTOS);
    }

    @Override
    public ServiceResult<UserRoleDTO> createDeliverCheckRole(String orgId) {
        // 设置参数
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setOrgId(orgId);
        // 创建角色和权限, 并返回结果
        return this.createRoleByRolePermsEnum(organizationDTO, RolePermsEnum.DELIVER_CHECK);
    }

    @Override
    public ServiceResult<List<String>> findRoleIdByCondition(UserRoleDTO userRoleDTO) {
        // 校验参数
        if (userRoleDTO == null) {
            return ServiceResult.fail("参数为空");
        }
        // 查询
        ServiceResult<List<UserRoleDTO>> serviceResult = this.selectByCondition(userRoleDTO);
        // 设置返回值
        if (!serviceResult.isSuccess()) {
            return ServiceResult.fail(serviceResult.getMsg());
        }
        List<UserRoleDTO> userRoleDTOS = serviceResult.getData();
        if (CollectionUtils.isEmpty(userRoleDTOS)) {
            return ServiceResult.success();
        }
        // 设置返回值
        List<String> roleIds = userRoleDTOS.stream().map(UserRoleDTO::getRoleId).distinct().collect(Collectors.toList());
        return ServiceResult.success(roleIds);
    }

    @Override
    public ServiceResult<Void> resetRolePerms(String roleName) {
        // 校验参数
        if (StringUtils.isBlank(roleName)) {
            return ServiceResult.fail("参数为空");
        }
        RolePermsEnum rolePermsEnum = RolePermsEnum.getByName(roleName);
        if (rolePermsEnum == null || StringUtils.isBlank(rolePermsEnum.getPerms())) {
            return ServiceResult.fail(String.format("没有配置对应的权限,无法重置. 角色名称=%s", roleName));
        }
        // 设置查询参数
        UserRoleDTO roleQuery = new UserRoleDTO();
        roleQuery.setName(roleName);
        List<String> roleIdsByName = this.findRoleIdByCondition(roleQuery).getData();
        if (CollectionUtils.isNotEmpty(roleIdsByName)) {
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
            rolePermissionDTO.setPermission(rolePermsEnum.getPerms());
            List<List<String>> roleIdsList = ListUtils.partition(roleIdsByName, CommonConstant.PARTITION_SIZE);
            for (List<String> roleIds : roleIdsList) {
                rolePermissionService.updateByIds(roleIds, rolePermissionDTO);
            }
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Void> resetAdminAndSeniorRole() {
        // 设置查询参数
        UserRoleDTO adminRoleQuery = new UserRoleDTO();
        adminRoleQuery.setName(RolePermsEnum.ADMIN.getName());
        adminRoleQuery.setType(RolePermsEnum.ADMIN.getType());
        UserRoleDTO seniorRoleQuery = new UserRoleDTO();
        seniorRoleQuery.setName(RolePermsEnum.SENIOR_ADMIN.getName());
        seniorRoleQuery.setType(RolePermsEnum.SENIOR_ADMIN.getType());
        // 查询
        List<String> adminRoleIds = this.findRoleIdByCondition(adminRoleQuery).getData();
        List<String> seniorRoleIds = this.findRoleIdByCondition(seniorRoleQuery).getData();
        // 更新系统管理员权限
        if (CollectionUtils.isNotEmpty(adminRoleIds)) {
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
            rolePermissionDTO.setPermission(JSON.toJSONString(permissionUtil.getAllPermission()));
            List<List<String>> adminRoleIdsList = ListUtils.partition(adminRoleIds, CommonConstant.PARTITION_SIZE);
            for (List<String> roleIds : adminRoleIdsList) {
                rolePermissionService.updateByIds(roleIds, rolePermissionDTO);
            }
        }
        // 更新高级管理员权限
        if (CollectionUtils.isNotEmpty(seniorRoleIds)) {
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
            rolePermissionDTO.setPermission(JSON.toJSONString(permissionUtil.getAllPermission()));
            List<List<String>> seniorRoleIdsList = ListUtils.partition(seniorRoleIds, CommonConstant.PARTITION_SIZE);
            for (List<String> roleIds : seniorRoleIdsList) {
                rolePermissionService.updateByIds(roleIds, rolePermissionDTO);
            }
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<UserRoleDTO> createOrUpdateRoleAndPerms(String orgId, RolePermsEnum rolePermsEnum) {
        // 校验并设置参数
        String roleId = null;
        if (RolePermsEnum.ADMIN.getName().equals(rolePermsEnum.getName())) {
            // 系统管理员
            // 通过公司id查询高级管理员角色id
            roleId = this.getAdminRole(orgId).getData();
        } else if (RolePermsEnum.SENIOR_ADMIN.getName().equals(rolePermsEnum.getName())) {
            // 高级管理员
            // 通过公司id查询高级管理员角色id
            roleId = this.getSeniorAdminRole(orgId).getData();
        } else {
            return ServiceResult.fail("角色配置不存在");
        }

        // 判断角色是否存在
        if (StringUtils.isBlank(roleId)) {
            // 角色不存在, 则新增
            ServiceResult<UserRoleDTO> result = this.createSpecialRole(rolePermsEnum.getName(), orgId);
            // 设置返回值
            return ServiceResult.success(result.getData());

        } else {
            // 角色存在
            // 查询角色对应的权限
            RolePermissionDTO existRolePermission = rolePermissionService.selectByOrgIdAndRoleId(orgId, roleId).getData();
            // 设置参数
            Date now = DataBaseUtil.getDate();
            RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
            rolePermissionDTO.setPermission(JSON.toJSONString(permissionUtil.getAllPermission()));
            rolePermissionDTO.setUpdateTime(now);
            if (existRolePermission == null) {
                // 新增权限
                rolePermissionDTO.setRoleId(roleId);
                rolePermissionDTO.setOrgId(orgId);
                rolePermissionDTO.setCreateTime(now);
                rolePermissionService.insertSelective(rolePermissionDTO);

            } else {
                // 更新权限
                rolePermissionDTO.setRolePermissionId(existRolePermission.getRolePermissionId());
                rolePermissionService.updateByPrimaryKeySelective(rolePermissionDTO);
            }
            // 设置返回值
            UserRoleDTO roleDTO = new UserRoleDTO();
            roleDTO.setRoleId(roleId);
            return ServiceResult.success(roleDTO);
        }
    }

    /**
     * 通过角色名称创建特殊角色
     *
     * @param name
     * @param orgId
     * @return ServiceResult<UserRoleDTO>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @version v1.0
     * @date 2022/3/21 14:52
     */
    private ServiceResult<UserRoleDTO> createSpecialRole(String name, String orgId) {
        // 设置参数
        Date now = DataBaseUtil.getDate();
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setOrgId(orgId);
        organizationDTO.setCreateTime(now);
        organizationDTO.setUpdateTime(now);
        if (RolePermsEnum.ADMIN.getName().equals(name)) {
            // 创建系统管理员
            return this.createAdminRole(organizationDTO);
        } else if (RolePermsEnum.SENIOR_ADMIN.getName().equals(name)) {
            // 创建高级管理员
            return this.createRoleByRolePermsEnum(organizationDTO, RolePermsEnum.SENIOR_ADMIN);
        }
        return ServiceResult.fail("找不到对应的角色权限配置");
    }

    /**
     * 通过角色枚举创建角色
     *
     * @param organizationDTO
     * @param rolePermsEnum
     * @return ServiceResult<UserRoleDTO>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @version v1.0
     * @date 2022/3/21 15:03
     */
    private ServiceResult<UserRoleDTO> createRoleByRolePermsEnum(OrganizationDTO organizationDTO, RolePermsEnum rolePermsEnum) {
        // 保存特殊角色
        UserRoleDTO userRoleDTO = new UserRoleDTO();
        userRoleDTO.setOrgId(organizationDTO.getOrgId());
        userRoleDTO.setName(rolePermsEnum.getName());
        userRoleDTO.setType(rolePermsEnum.getType());
        userRoleDTO.setContent(rolePermsEnum.getContent());
        userRoleDTO.setUpdateTime(organizationDTO.getUpdateTime());
        userRoleDTO.setOperatorId(organizationDTO.getOperatorId());
        userRoleDTO.setCreateTime(organizationDTO.getUpdateTime());
        userRoleDTO.setCreatorId(organizationDTO.getOperatorId());
        this.saveUserRoleBase(userRoleDTO);

        // 创建角色对应的权限关联
        RolePermissionDTO rolePermissionDTO = new RolePermissionDTO();
        rolePermissionDTO.setRoleId(userRoleDTO.getRoleId());
        rolePermissionDTO.setOrgId(userRoleDTO.getOrgId());
        // 设置权限
        if (RolePermsEnum.ADMIN.getName().equals(rolePermsEnum.getName())
                || RolePermsEnum.SENIOR_ADMIN.getName().equals(rolePermsEnum.getName())) {
            rolePermissionDTO.setPermission(JSON.toJSONString(permissionUtil.getAllPermission()));
        } else {
            rolePermissionDTO.setPermission(rolePermsEnum.getPerms());
        }
        rolePermissionDTO.setUpdateTime(userRoleDTO.getUpdateTime());
        rolePermissionDTO.setOperatorId(userRoleDTO.getOperatorId());
        rolePermissionDTO.setCreateTime(userRoleDTO.getUpdateTime());
        rolePermissionDTO.setCreatorId(userRoleDTO.getOperatorId());
        rolePermissionService.insertSelective(rolePermissionDTO);
        // 返回结果
        return ServiceResult.success(userRoleDTO);
    }


    /**
     * 获取单个角色id
     *
     * @param userRoleDTO
     * @return ServiceResult<String>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @version v1.0
     * @date 2022/3/21 10:58
     */
    private ServiceResult<String> getRoleIdByCondition(UserRoleDTO userRoleDTO) {
        // 校验参数
        if (userRoleDTO == null || StringUtils.isBlank(userRoleDTO.getOrgId())) {
            return ServiceResult.fail("参数为空");
        }
        // 查询
        ServiceResult<List<String>> result = this.findRoleIdByCondition(userRoleDTO);
        // 设置返回值
        if (result.isSuccess()) {
            return ServiceResult.success(CollectionUtils.isNotEmpty(result.getData()) ? result.getData().get(0) : null);
        }
        return ServiceResult.fail(result.getMsg());
    }

    @Override
    public ServiceResult<List<String>> checkRoleExistAndSave(String orgId, List<String> nameList) {
        List<String> newRoleIdList = new ArrayList<>();
        for (String roleName : nameList) {
            UserRoleDTO userRoleDTO = new UserRoleDTO();
            userRoleDTO.setName(roleName);
            userRoleDTO.setOrgId(orgId);
            ServiceResult<List<UserRoleDTO>> result = selectByCondition(userRoleDTO);
            List<UserRoleDTO> userRoleDTOList = result.getData();
            // 不存在则保存
            if (CollectionUtils.isEmpty(userRoleDTOList)) {
                UserRoleDTO saveRoleDTO = new UserRoleDTO();
                saveRoleDTO.setName(roleName);
                saveRoleDTO.setOrgId(orgId);
                ServiceResult<String> userRoleResult = saveUserRole(saveRoleDTO);
                String roleId = userRoleResult.getData();
                newRoleIdList.add(roleId);
            } else {
                UserRoleDTO roleDTO = result.getData().get(0);
                newRoleIdList.add(roleDTO.getRoleId());
            }
        }
        return ServiceResult.success(newRoleIdList);

    }

    @Override
    public ServiceResult<List<UserRoleDTO>> getRoleListByIdList(List<String> roleIdList) {
        return ServiceResult.success(userRoleConvert.dos2Dtos(userRoleDao.getRoleListByIdList(roleIdList)));
    }
}
